package org.agent.action;

import java.util.Date;

import org.agent.common.Constants;
import org.agent.common.MD5;
import org.agent.pojo.User;

public class LoginAction extends BaseAction {
	private User user;//接收表单的数据
	
	//index
	public String index(){
		
		return SUCCESS;
	}
	//登入
	public String login(){
		System.out.println("进入login");
		if(user!=null){
			//密码加密的处理
			System.out.println(this.getUserService());
			user.setUserPassword(MD5.MD5Encode(user.getUserPassword()));
			
			User userTmp = this.getUserService().getLoginUser(user);
			if(userTmp!=null){
							System.out.println(userTmp.getUserName()+userTmp.getUserPassword());	
				//保存session
				this.getRequest().getSession().setAttribute(Constants.SESSION_USER, userTmp);
				userTmp.setLastLoginTime(new Date());//更新登入时间
				this.getUserService().modifyUser(userTmp);
				return SUCCESS;
			}else{
				System.out.println("登入失败");//d41d8cd98f00b204e9800998ecf8427e(String)
											  //d41d8cd98f00b204e9800998ecf8427e
				return INPUT;
			}
		}else{
			return INPUT;
		}
	}
	
	//验证
	public String check(){
		
		/*success:function(data){//服务器返回的data
				if("noExitUserCode"==data){
				alert("对不起,账户不存在!");
				}else if("errorpwd"==data){
					alert("对不起,密码!");
				}else if("failed"==date){
					alert("对不起,系统错误!");
				}else if("success"==data){
					flag=true;
				}
			}
		 * 
		 */
		System.out.println("进入check");
		String flag = "failed";
		if(user!=null&&user.getUserCode()!=""){
			//密码加密的处理
			user.setUserPassword(MD5.MD5Encode(user.getUserPassword()));
			
			int n =	this.getUserService().isExitLoginUser(user);
			if(n==0){
				flag = "noExitUserCode";
			}else if (this.getUserService().getLoginUser(user)==null) {
				flag = "errorpwd";
			}else {
				flag = "suc";
			}
		}
		System.out.println(flag);
		this.getOut().print(flag);//ajax接收
		return null;//返回null，struts2不在进行页面的显示处理
		
	}
	
	public String main(){
		//可以加入权限验证
		return SUCCESS;
		
	}
	//处理修改密码
	public void modifypwd(){
		System.out.println("进入modifypwd处理修改密码");
		//user:页面传输过来的；usertmp：已登入用户,密码是已经加密了的
		User usertmp =	(User) this.getRequest().getSession().getAttribute(Constants.SESSION_USER);
		//老密码用userName属性传递
		System.out.println("username-->"+user.getUserName());
		System.out.println("usertemname-->"+usertmp.getUserPassword());
																//usertmp：密码是已经加密了的，直接比较
		boolean b = MD5.MD5Encode(user.getUserName()).equals(usertmp.getUserPassword());
		System.out.println(b);
		if(b){									
			usertmp.setUserPassword(MD5.MD5Encode(user.getUserPassword()));
			if(this.getUserService().modifyUser(usertmp)>0){
				System.out.println("修改成功");
				this.getOut().print("success");
				this.getOut().flush();
				this.getOut().close();
			}
		}
	}
	//退出
	public String exit(){
		this.getRequest().getSession().invalidate();
		this.getRequest().getSession().removeAttribute(Constants.SESSION_USER);
		return SUCCESS;
	}
	
	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	
	
}
